package com.hfzy.ihk.web.aliyuncall.job;

import com.hfzy.ihk.common.util.string.StringTools;
import com.hfzy.ihk.web.aliyuncall.biz.PushDataToBLBiz;
import com.hfzy.ihk.web.aliyuncall.constant.RedisFields;
import com.hfzy.ihk.web.aliyuncall.constant.RedisKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;

/**
 *检查推送到保利的数据是否成功推送，每3分钟跑一次将推送失败的呼叫数据重新推送，每10分钟跑一次将推送失败的录音URL数据重新推送
 */
@Component
public class CheckPushBLJob {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    PushDataToBLBiz pushDataToBLBiz;

    /**
     * 检查推送数据到保利失败的job 三分钟跑一次 这里不需要了
     */
   // @Scheduled(cron = "0 0/3 * * * ?")
    public void rePushRecord(){
        //获得推送失败的数据
        Set<String> recordFailSet = redisTemplate.opsForSet().members(RedisKey.PUSH_RECORD_TO_BL_FAILED_SET);
        if(recordFailSet!=null&&recordFailSet.size()>0){
            for(String sessionId:recordFailSet){
                if(StringTools.isEmpty(sessionId)||"".equals(sessionId)){
                    redisTemplate.opsForSet().remove(RedisKey.PUSH_RECORD_TO_BL_FAILED_SET,sessionId);
                    continue;
                }

                Map<String,String> callHistoryMap = redisTemplate.opsForHash().entries(RedisKey.CALL_HISTORY_RPIX+sessionId);
                if(StringTools.isNotempty(callHistoryMap)&&callHistoryMap.size()>0){//不为空，推送
                    pushDataToBLBiz.jobPushData(callHistoryMap);
                }else{//为空，删了防止堆积
                    redisTemplate.opsForSet().remove(RedisKey.PUSH_RECORD_TO_BL_FAILED_SET,sessionId);
                }
            }
        }
    }


    /*
    检查推送录音到保利失败的Job 五分钟跑一次
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    public void rePushRecordFileUrl(){
        Set<String> recordFailSet = redisTemplate.opsForSet().members(RedisKey.PUSH_URL_TO_BL_FAILED_SET);
        if(recordFailSet!=null&&recordFailSet.size()>0){
            for(String sessionId:recordFailSet){
                Map<String,String> callHistoryMap = redisTemplate.opsForHash().entries(RedisKey.CALL_HISTORY_RPIX+sessionId);
                if(StringTools.isNotempty(callHistoryMap)&&callHistoryMap.size()>0&&callHistoryMap.get(RedisFields.CALL_HISTORY_RECORD_FILE_URL)!=null
                        &&!"NULL".equals(callHistoryMap.get(RedisFields.CALL_HISTORY_RECORD_FILE_URL)!=null)
                        &&"11".equals(callHistoryMap.get(RedisFields.CALL_HISTORY_COMMIT_TO))){//不为空，推送,为爱家才推
                    pushDataToBLBiz.jobPushRecordUrl(sessionId,callHistoryMap.get(RedisFields.CALL_HISTORY_RECORD_FILE_URL));
                }else{//为空，删了防止堆积
                    redisTemplate.opsForSet().remove(RedisKey.PUSH_URL_TO_BL_FAILED_SET,sessionId);
                }
            }
        }
    }
}
